package com.mipo.shiro.filter;

import java.util.Set;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;


public class TspAdminRolesAuthorizationFilter extends AuthorizationFilter {

	@Override
	protected boolean isAccessAllowed(ServletRequest request,
			ServletResponse response, Object mappedValue) throws Exception {
		 	Subject subject = getSubject(request, response);
	        String[] rolesArray = (String[]) mappedValue;
	        String loginUserInfo = (String)SecurityUtils.getSubject().getSession().getAttribute("SESSION_USER");
	        if (loginUserInfo!=null) {
				String username = loginUserInfo;
				String sysAdmin = "admin_system";
				if (sysAdmin.trim().equals(username)) {
					return true;
				}
			}
	        if (rolesArray == null || rolesArray.length == 0) {
	            //no roles specified, so nothing to check - allow access.
	            return true;
	        }
	        
	        Set<String> roles = CollectionUtils.asSet(rolesArray);
	        
	        for (String role : roles) {
				if (subject.hasRole(role)) {
					return true;
				}
			}
	        
	        return false;
	}

}
